Risk TrackerThis Risk Tracker Pine Script provides traders with a customizable tool for tracking and managing trade risk directly on their chart. The script is designed to accommodate both futures and crypto trades, allowing you to monitor risk and reward parameters, adjust contract sizes, and manage leverage in real-time.
Key Features:
1. Trade Direction and Risk-Reward Ratio:
	• Select between Long or Short trade directions.
	• Set a custom Risk-Reward Ratio (RRR) to calculate potential profit and loss levels based on your trade setup.
2. Customizable Parameters:
	• Input fields for contract size, leverage, margin, and maximum drawdown allow you to adjust the risk settings depending on the market you are trading.
	• You can toggle between using a dollar-based or percentage-based risk calculation depending on whether you’re trading futures (USD-based) or crypto.
3. Real-time Stop-Loss and Take-Profit Calculation:
	• The script automatically calculates and draws the Stop-Loss (SL) and Take-Profit (TP) levels on the chart based on your entry price and selected risk settings.
	• The color of the SL and TP lines is customizable, allowing you to visually distinguish profit and loss levels.
4. Historical Price Levels:
	• If there is no active trade, the script scans historical price data to find the last instances when the price hit the predefined stop-loss or take-profit levels, helping you understand past price behavior.
5. Risk Management Table:
	• A summary table is displayed on the chart, showing the key metrics of your trade, including:
	• Tick value and Dollar value for futures.
	• Margin and Leverage for crypto.
	• Risk-Reward Ratio, Entry price, Risk and Profit in USD or percentage terms.
	• The table dynamically updates based on the current trade status.
6. Extended Chart Visualization:
	• Option to extend the SL and TP lines to the left of the chart, allowing you to easily view these levels across multiple timeframes and bars.
This script helps ensure you are always aware of your trade’s risk profile, providing a clear and visual representation of potential profit and loss, both in terms of percentage and dollar value. Ideal for futures and crypto traders who rely on precise risk management to maintain profitability.
Cerca negli script per " TABLE"
Decline and Rise Detective [CHE]Decline and Rise Detective  
 TradingView Indicator (Best Timeframe: 1H or Higher) 
 1. Introduction 
The "Decline and Rise Detective  " is a TradingView indicator designed to identify the hours within a trading day that experience the largest price declines and rises. This indicator provides a visual representation of this data, offering traders valuable insights into the most frequent hours for significant price movements. It is most effective when used with a timeframe of 1 hour or greater.
 2. Key Features of the Indicator 
2.1. Display Options
Display Option: Users can choose between two display options:
Label: Displays the information as a text label directly on the chart.
Table: Displays the information in a table format in the top right corner of the chart.
2.2. Time Zone Settings
Time Zone: The indicator allows the user to manually set the time zone or use the exchange's time zone.
Time Zone Offset: Adjust the time zone via a UTC offset.
2.3. Day Change Detection
The indicator automatically detects the change between trading days to ensure data is correctly assigned.
 3. Analysis of Price Declines and Rises 
3.1. Calculation of Largest Declines and Rises
The indicator compares the high and low of each hour to determine the largest decline and rise within a trading day.
3.2. Frequency Counting
For each hour of the day, the number of times the largest declines and rises occur is counted to identify the hours with the most significant price movements.
3.3. Data Sorting
The hours are sorted by the number of occurrences of declines and rises to highlight the most frequent hours. This sorting was implemented using the MA Sorter function, inspired by Duyck's Array Sorter. Special thanks to Duyck for providing the Array Sorter on TradingView, which greatly influenced this feature 
 4. Interpretation and Trading Applications 
4.1. Identifying High Volatility Periods
The hours identified by the indicator as having the most frequent and significant price movements are typically periods of high volatility. These periods are crucial for traders who seek to capitalize on market fluctuations.
4.2. Determining Optimal Trade Entries
Long Trades: The hours with the most significant price rises can be used to identify optimal times to enter long positions.
Short Trades: Conversely, the hours with the most significant price declines can indicate good opportunities for short trades.
4.3. Display of Top 5 Hours
The indicator shows the five hours with the most declines and rises.
Depending on the selected display option, this information is shown either as a text label or as a table in the chart.
4.4. Background Color
The background color of the chart changes at day change to clearly mark it.
 5. Application of the Indicator 
5.1. Trading Use
Traders can use the indicator to identify time windows with high volatility and adjust their trading strategies accordingly. This allows for more informed decisions on when to go long or short, depending on the market conditions during those hours.
5.2. Customization Options
Various input options allow the user to customize the indicator to fit personal needs and trading hours.
 6. Summary 
The "Decline and Rise Detective  " indicator is a powerful tool for analyzing hourly price movements in the markets. By providing detailed information on the most frequent hours for significant price declines and rises, this indicator offers valuable insights into periods of high volatility. Traders can use this data to make more informed decisions on entering long or short trades. It is particularly effective when used with timeframes of 1 hour or greater.
Best regards and happy trading
Chervolino
HMA Z-Score Probability Indicator by Erika BarkerThis indicator is a modified version of SteverSteves's original work, enhanced by Erika Barker. It visually represents asset price movements in terms of standard deviations from a Hull Moving Average (HMA), commonly known as a Z-Score.
 Key Features: 
 Z-Score Calculation:  Measures how many standard deviations the current price is from its HMA.
Hull Moving Average (HMA): This moving average provides a more responsive baseline for Z-Score calculations.
Flexible Display: Offers both area and candlestick visualization options for the Z-Score.
Probability Zones: Color-coded areas showing the statistical likelihood of prices based on their Z-Score.
Dynamic Price Level Labels: Displays actual price levels corresponding to Z-Score values.
Z-Table: An optional table showing the probability of occurrence for different Z-Score ranges.
Standard Deviation Lines: Horizontal lines at each standard deviation level for easy reference.
 How It Works: 
The indicator calculates the Z-Score by comparing the current price to its HMA and dividing by the standard deviation. This Z-Score is then plotted on a separate pane below the main chart.
Green areas/candles: Indicate prices above the HMA (positive Z-Score)
Red areas/candles: Indicate prices below the HMA (negative Z-Score)
Color-coded zones:
Green: Within 1 standard deviation (high probability)
Yellow: Between 1 and 2 standard deviations (medium probability)
Red: Beyond 2 standard deviations (low probability)
The HMA line (white) shows the trend of the Z-Score itself, offering insight into whether the asset is becoming more or less volatile over time.
Customization Options:
Adjust lookback periods for Z-Score and HMA calculations
Toggle between area and candlestick display
Show/hide probability fills, Z-Table, HMA line, and standard deviation bands
Customize text color and decimal rounding for price levels
 Interpretation: 
This indicator helps traders identify potential overbought or oversold conditions based on statistical probabilities. Extreme Z-Score values (beyond ±2 or ±3) often suggest a higher likelihood of mean reversion, while consistent Z-Scores in one direction may indicate a strong trend.
By combining the Z-Score with the HMA and probability zones, traders can gain a nuanced understanding of price movements relative to recent trends and their statistical significance.
Stef's Enterprise Value CalculatorI have learned the hard way why Enterprise Value is far more superior than Market Cap. That's why I made this indicator, but more importantly, why I added several features that other similar indicators just don't have. The key thing is to not just show you Enterprise Value of a company (it's true worth) but also the capability to see that line colored in a specific way, with key stats as a neat table, and the ability to chart the key facts that go into Enterprise Value, which are debt and cash.
I'll say it again: Market Cap is not nearly as good as Enterprise Value. Don't get tricked by what Market Cap does NOT show you and instead focus on Enterprise Value. I hope my indicator, and the features you see below, help investors and traders all over the world better understand this.
 Here are the key features: 
 Enterprise Value Indicator Features:
 
1. Real-Time Enterprise Value (EV) Display: Track the EV of a company directly on your chart, providing a comprehensive measure of its true market value.
2. Custom Color Trends: Customize the color of your EV line based on specific trends you’re monitoring, allowing for personalized and insightful visual analysis.
3. Debt & Cash Visualization: Plot both debt and cash & equivalents on the same chart, offering a clear and concise view of a company’s financial health.
4. Key Metrics Table: View a table displaying essential metrics including:
- Average EV
- Highest EV
- Lowest EV
- MC-EV (Market Cap minus Enterprise Value)
MC-EV Charting: Easily chart MC-EV to understand how much debt a company has relative to its market cap, providing insight into financial leverage and growth potential.
 Why MC-EV Matters:  This metric is crucial for evaluating a company’s financial risk and operational efficiency, giving you an edge in making informed investment decisions.
Thanks for reading and I hope you find some value in this! More updates to come.
Day-of-Week PerformanceThis Pine Script indicator calculates and displays the average performance for each weekday over a specified lookback period on a chart. The performance is computed based on the percentage change from the open to the close price of each day.
Features:
    Lookback Period:
        Input field to specify the number of days to look back for calculating performance. The default is set to 756 days.
    Performance Calculation:
        Calculates the average percentage change from open to close for each weekday (Monday through Friday) within the specified lookback period.
    Histogram Plots:
        Displays histograms on the chart for each weekday. Each histogram represents the average performance of that day of the week.
        Histograms are plotted with distinct colors:
            Monday: Blue
            Tuesday: Red
            Wednesday: Green
            Thursday: Orange
            Friday: Purple
    Performance Table:
        A table is displayed in the top-right corner of the chart showing the average percentage performance for each weekday.
        The table updates with the lookback period and the calculated average performance values for each weekday.
        Positive performance values are shown in green, and negative values are shown in red.
This indicator helps visualize day-of-the-week performance trends, providing insights into which days typically perform better or worse over the specified period.
Portfolio Index Generator [By MUQWISHI]▋ INTRODUCTION: 
The “Portfolio Index Generator” simplifies the process of building a custom portfolio management index, allowing investors to input a list of preferred holdings from global securities and customize the initial investment weight of each security. Furthermore, it includes an option for rebalancing by adjusting the weights of assets to maintain a desired level of asset allocation. The tool serves as a comprehensive approach for tracking portfolio performance, conducting research, and analyzing specific aspects of portfolio investment. The output includes an index value, a table of holdings, and chart plotting, providing a deeper understanding of the portfolio's historical movement.
_______________________
 ▋ OVERVIEW: 
  
The image can be taken as an example of building a custom portfolio index. I created this index and named it “My Portfolio Performance”, which comprises several global companies and crypto assets. 
_______________________
 ▋ OUTPUTS: 
The output can be divided into 4 sections:
1. Portfolio Index Title (Name & Value). 
2. Portfolio Specifications.
3. Portfolio Holdings. 
4. Portfolio Index Chart.
  
1. Portfolio Index Title, displays the index name at the top, and at the bottom, it shows the index value, along with the chart timeframe, e.g., daily change in points and percentage.
  
2. Portfolio Specifications, displays the essential information on portfolio performance, including the investment date range, initial capital, returns, assets, and equity.
  
3. Portfolio Holdings, a list of the holding securities inside a table that contains the ticker, average entry price, last price, return percentage of the portfolio's initial capital, and customized weighted percentage of the portfolio. Additionally, a tooltip appears when the user passes the cursor over a ticker's cell, showing brief information about the company, such as the company's name, exchange market, country, sector, and industry. 
  
4. Index Chart, display a plot of the historical movement of the index in the form of a bar, candle, or line chart.
  
_______________________
 ▋ INDICATOR SETTINGS: 
 Section(1): Style Settings 
  
(1) Naming the index.
(2) Table location on the chart and cell size.
(3) Sorting Holdings Table. By securities’ {Return(%) Portfolio, Weight(%) Portfolio, or Ticker Alphabetical} order.
(4) Choose the type of index: {Equity or Return (%)}, and the plot type for the index: {Candle, Bar, or Line}.
(5) Positive/Negative colors. 
(6) Table Colors (Title, Cell, and Text).
(7) To show/hide any indicator’s components.
 Section(2): Performance Settings 
  
(1) Calculation window period: from DateTime to DateTime.
(2) Initial Capital and specifying currency. 
(3) Option to enable portfolio rebalancing in {Monthly, Quarterly, or Yearly} intervals.
 Section(3): Portfolio Holdings 
  
(1) Enable and count security in the investment portfolio.
(2) Initial weight of security.  For example, if the initial capital is $100,000 and the weight of XYZ stock is 4%, the initial value of the shares would be $4,000. 
(3) Select and add up to 30 symbols that interested in.
Please let me know if you have any questions.
Multi Asset Histogram [ChartPrime]Multi Asset Histogram Indicator 
 Overview: 
The "Multi Asset Histogram" indicator provides a comprehensive visualization of the performance of multiple assets relative to each other. By calculating a score for each asset and displaying it in a histogram format, this indicator helps traders quickly identify the trends, dominant asset and the average performance of the assets in the selected group.
 Key Features: 
 ◆ Multi-Asset Score Calculation: 
The indicator calculates a trend score for each selected asset based on the price source (e.g., hl2).
The trend score is determined by comparing the current price to the prices over the past bars back defined by user, adding or subtracting points based on whether the current price is higher or lower than previous prices.
 
// Score Function
trscore(src) =>
    total = 0.0
    for i = 1 to 50 
        total += (src >= nz(src ) ? 1 : -1)
    total
 
 ◆ Flexible Symbol Input: 
Traders can input up to 10 different symbols (e.g., BTCUSD, ETHUSD, etc.) to be included in the histogram analysis.
  
 ◆ Dynamic Visualization: 
A histogram is plotted for each asset, with bars colored based on the score, providing a clear visual representation of the relative performance.
Color gradients from red to aqua indicate the performance, with red representing negative scores and aqua representing positive scores.
 ◆ Adaptive Histogram Lines: 
The width and placement of histogram lines adapt based on the calculated scores, ensuring clear visualization regardless of the values.
Dashed lines represent the mean score of all assets, helping traders identify the overall market trend.
 ◆Detailed Labels and Values: 
Labels are placed on the histogram to display the exact score for each asset.
  
Mean value and zero line labels provide additional context for the overall performance.
  
 ◆ Visual Scaling Lines: 
Zero line and mean line are clearly marked, helping traders understand the distribution and scale of scores.
Scales on the left and right of the histogram indicate the performance range.
  
 ◆ Informative Table: 
A table is displayed on the chart, showing the dominant asset (the one with the highest score) and the mean score of all assets.
The table updates dynamically to reflect real-time changes in asset performance.
  
 ◆ Settings: 
 
 Length: The value of number bars back is greater or less than the current value of the source
 Source: The price source to be used for score calculation (e.g., hl2).
 Symbols: Up to 10 different asset symbols can be input for analysis.
 
 Usage Notes: 
This indicator is useful for traders who monitor multiple assets simultaneously and need a quick visual reference to identify the strongest and weakest performers.
The color coding and dynamic labels make it easy to interpret the relative performance and make informed trading decisions.
 This indicator is designed to enhance multi-asset analysis by providing a clear, visual representation of each asset's performance relative to the others, making it easier to identify trends and dominant assets in the market.
Market Cap / Revenue RatioA variation of the P/S ratio, this script takes the future estimated revenue of the current stock versus it's Market Cap. It then compares the aforementioned Market Cap:Revenue ratio against a market bellwether's corresponding ratio (MSFT by default) to determine the following:
- Light green when the ratio is extremely low (Stock is very undervalued)
- Green when the ratio is low (Stock's multiple is lower by 20-50%)
- Blue when the ratio is close to the benchmark (Stock is fairly valued to benchmark multiple)
- Red when the ratio is high (Stock's mulitple is higher by 50% or more)
- Dark red when the ratio is extremely high (Stock is very overvalued)
CONFIGURABLE
- Full Table: Show the entire calculation table
- Minimalist: Go minimal and show only the ratio and color code
- Show Benchmark Multiple: Show the multiple ratio calculated between the current stock and the benchmark stock (MSFT by default)
NOTES
- When calculating the Market Cap, TradingView sometimes under-reports the number of shares and thus skews the Market Cap too low. This seems to happen for stocks with multiple share classes like GOOGL so be mindful that the data can be wrong for these kinds of stocks. You can check on this by going into the Indicator's Settings and select Show Full Table which will show the number of shares outstanding reported by TradingView.
- For certain stocks such as foreign ADRs, there won't be a future revenue estimate so the script will automatically use the Total Revenue for the most recent Quarter in these cases 
Divergence Detector [TradingFinder] RSI + MACD + AO Oscillator 🔵 Introduction 
🟣 Understanding Divergence 
As mentioned, divergence occurs in technical analysis when a stock's price behaves contrary to indicators on the price chart. Divergence can signify either a reversal of the stock's trend or a continuation of the previous trend correction. 
Divergences can act as reversal patterns or continuation patterns. Moreover, divergences can be utilized to identify potential support and resistance levels.
For instance, when an indicator is trending upwards and positive, but the price is declining and trending downwards, divergence occurs. Divergence in a stock indicates trader indecision in buying and selling and warns traders to reconsider their decisions regarding buying or holding the stock. 
Divergence aids analysts in identifying critical price points. In indicator divergences, it serves as a potent signal in the realm of technical analysis.
🟣 Types of Divergence 
1.Regular Divergence
    o	Positive Regular Divergence (RD+)
    o	Negative Regular Divergence (RD-)
2.Hidden Divergence
    o	Positive Hidden Divergence (HD+)
    o	Negative Hidden Divergence (HD-)
3.Time Divergence
 Key Note : This indicator is specifically designed to identify "Regular Divergence" only. Therefore, the following explanation pertains to this type of divergence.
🔵 Regular Divergence/Convergence 
Regular Divergence(Convergence) occurs due to conflicting behavior between the indicator and the price chart, typically at the end of a trend. Recognizing Regular Divergence suggests an anticipation of a trend reversal or a pattern resembling a reversal.
  
🟣 Positive Regular Divergence (RD+) 
In contrast to negative divergence, positive Regular Divergence occurs at the end of a downtrend and between two price lows. It manifests when the price forms a new low on the price chart, but the indicator fails to recognize it. 
Positive Regular Divergence indicates strong buying pressure and weak selling pressure. Following the identification of positive divergence on the chart, one can anticipate a price increase for the examined stock.
  
🟣 Negative Regular Divergence (RD-) 
This type of Regular Divergence emerges between two price highs during an uptrend. A new high is formed on the price chart, but the indicator fails to acknowledge it. This scenario indicates negative Regular Divergence. 
The likelihood of a subsequent market downturn is high. Negative divergence signifies strong selling pressure and weak buying pressure, suggesting an unfavorable future for the stock.
  
🔵 How to use 
By utilizing the "Fractal Period" input, you can specify your desired periods for identifying divergences.
Additionally, through the "Divergence Detect Method" feature, you can choose which oscillators (MACD, RSI, or AO) to base divergence identification on.
 Divergence in MACD Oscillator :
Divergence in the MACD indicator occurs when the price chart and the MACD line form a noticeable opposing pattern, meaning the price moves contrary to the MACD line. In this scenario, one expects a reversal in price direction.
  
 Divergence in RSI Oscillator :
If divergence occurs during a downtrend on the price chart (two consecutive lows, with the second low being lower) and on the corresponding RSI point (two consecutive lows, with the second low being higher), it signifies positive Regular Divergence and implies a buying signal.
 
Conversely, if divergence occurs during an uptrend on the price chart (two consecutive highs, with the second high being higher) and on the corresponding RSI point (two consecutive highs, with the second high being lower), it indicates negative Regular Divergence, signaling a selling opportunity.
  
 Divergence in AO Oscillator :
The AO indicator calculates histograms similar to the AO base. It calculates the difference between the simple moving averages of 5 and 34 periods based on the median of each bar. Then, it plots the bars based on the difference. 
It then compares the histograms to detect peaks and troughs in the AO histograms and compares the identified peaks and troughs to the price. Whenever divergence is detected, it plots lines and arrows.
  
🔵 Table 
The table contains information on the functional features of this oscillator that you can utilize. Four categories of information are presented in the table: "Exist," "Consecutive," "Divergence Quality," and "Change Phase Indicator."
 Exist : 
If divergence exists, you'll see "+" in this row.
 Consecutive : 
Divergences may occur consecutively. If same-type divergences form within short intervals, you can observe the count in this row.
  
 Divergence Quality : Based on the number of consecutive divergences, their quality can be evaluated. If one divergence exists, its quality is considered "Normal." If two divergences exist, the quality is "Good," and if three or more divergences exist, the quality is considered "Strong."
 Change Phase Indicator : If a phase change occurs between two oscillation peaks formed based on divergence, this change is identified and displayed in this row.
  
WTI Crude Oil Lot Size Calculator by AdrianFx94Indicator on Trading Chart: Once you add this script to your trading chart (specifically a WTI Crude Oil chart), it appears as an indicator. This means it runs alongside the price data and other technical analysis tools you might be using.
Input Your Trading Parameters:
Balance (USD): You need to enter your trading account balance in USD. This is the amount of money you have in your account.
Risk Percentage (%): This is where you define the percentage of your account balance that you're willing to risk in a single trade. For example, if your account balance is $5000 and you set the risk percentage to 1%, you're willing to risk $50 on a trade.
Stop Loss Pip Size (Pip): Here, you enter the size of your stop loss in pips. A pip is a small measure of change in a currency pair in the forex market. In the context of WTI Crude Oil trading, it represents a small change in the price.
Automated Lot Size Calculation: Based on the inputs you provide, the script automatically calculates the lot size you should use for your trade. The calculation takes into account the balance you're willing to risk, the percentage of risk, and the stop loss size. This helps in managing risk by suggesting the amount of WTI Crude Oil you should trade (in lots) that aligns with your risk tolerance.
Display Results in a Table: The script generates a table displayed on the top right corner of your chart. This table shows:
Your entered balance (in USD).
The risk percentage you've set.
The calculated lot size, which indicates how many lots of WTI Crude Oil you can trade based on your risk management parameters.
Real-Time Updates: As this script is part of an indicator on your chart, it updates in real time. This means if your account balance changes or if you decide to adjust your risk parameters, you can re-enter these values, and the script will update the lot size accordingly.
This tool is particularly useful for WTI Crude Oil traders who follow strict risk management rules. By automating the calculation of the lot size, it saves time and helps in making informed and disciplined trading decisions.
Day/Week/Month Metrics (Zeiierman)█  Overview 
The  Day/Week/Month Metrics (Zeiierman)  indicator is a powerful tool for traders looking to incorporate historical performance into their trading strategy. It computes statistical metrics related to the performance of a trading instrument on different time scales: daily, weekly, and monthly. Breaking down the performance into daily, weekly, and monthly metrics provides a granular view of the instrument's behavior.
 The indicator requires the chart to be set on a daily timeframe. 
  
█  Key Statistics 
⚪ Day in month
The performance of financial markets can show variability across different days within a month. This phenomenon, often referred to as the "monthly effect" or "turn-of-the-month effect," suggests that certain days of the month, especially the first and last days, tend to exhibit higher than average returns in many stock markets around the world. This effect is attributed to various factors including payroll contributions, investment of monthly dividends, and psychological factors among traders and investors.
  
⚪  Edge 
The Edge calculation identifies days within a month that consistently outperform the average monthly trading performance. It provides a statistical advantage by quantifying how often trading on these specific days yields better returns than the overall monthly average. This insight helps traders understand not just when returns might be higher, but also how reliable these patterns are over time. By focusing on days with a higher "Edge," traders can potentially increase their chances of success by aligning their strategies with historically more profitable days.
  
⚪  Month 
Historically, the stock market has exhibited seasonal trends, with certain months showing distinct patterns of performance. One of the most well-documented patterns is the "Sell in May and go away" phenomenon, suggesting that the period from November to April has historically brought significantly stronger gains in many major stock indices compared to the period from May to October. This pattern highlights the potential impact of seasonal investor sentiment and activities on market performance.
  
⚪  Day in week 
Various studies have identified the "day-of-the-week effect," where certain days of the week, particularly Monday and Friday, show different average returns compared to other weekdays. Historically, Mondays have been associated with lower or negative average returns in many markets, a phenomenon often linked to the settlement of trades from the previous week and negative news accumulation over the weekend. Fridays, on the other hand, might exhibit positive bias as investors adjust positions ahead of the weekend.
  
⚪  Week in month 
The performance of markets can also vary within different weeks of the month, with some studies suggesting a "week of the month effect." Typically, the first and the last week of the month may show stronger performance compared to the middle weeks. This pattern can be influenced by factors such as the timing of economic reports, monthly investment flows, and options and futures expiration dates which tend to cluster around these periods, affecting investor behavior and market liquidity.
  
█  How It Works 
⚪  Day in Month 
For each day of the month (1-31), the script calculates the average percentage change between the opening and closing prices of a trading instrument. This metric helps identify which days have historically been more volatile or profitable.
 It uses arrays to store the sum of percentage changes for each day and the total occurrences of each day to calculate the average percentage change. 
⚪  Month 
The script calculates the overall gain for each month (January-December) by comparing the closing price at the start of a month to the closing price at the end, expressed as a percentage. This metric offers insights into which months might offer better trading opportunities based on historical performance.
 Monthly gains are tracked using arrays that store the sum of these gains for each month and the count of occurrences to calculate the average monthly gain. 
⚪  Day in Week 
Similar to the day in the month analysis, the script evaluates the average percentage change between the opening and closing prices for each day of the week (Monday-Sunday). This information can be used to assess which days of the week are typically more favorable for trading.
 The script uses arrays to accumulate percentage changes and occurrences for each weekday, allowing for the calculation of average changes per day of the week. 
⚪  Week in Month 
The script assesses the performance of each week within a month, identifying the gain from the start to the end of each week, expressed as a percentage. This can help traders understand which weeks within a month may have historically presented better trading conditions.
 It employs arrays to track the weekly gains and the number of weeks, using a counter to identify which week of the month it is (1-4), allowing for the calculation of average weekly gains. 
█  How to Use 
Traders can use this indicator to identify patterns or trends in the instrument's performance. For example, if a particular day of the week consistently shows a higher percentage of bullish closes, a trader might consider this in their strategy. Similarly, if certain months show stronger performance historically, this information could influence trading decisions.
  
 Identifying High-Performance Days and Periods 
 
 Day in Month & Day in Week Analysis:  By examining the average percentage change for each day of the month and week, traders can identify specific days that historically have shown higher volatility or profitability. This allows for targeted trading strategies, focusing on these high-performance days to maximize potential gains.
 Month Analysis:  Understanding which months have historically provided better returns enables traders to adjust their trading intensity or capital allocation in anticipation of seasonally stronger or weaker periods.
 Week in Month Analysis:  Identifying which weeks within a month have historically been more profitable can help traders plan their trades around these periods, potentially increasing their chances of success.
 
█  Settings 
 
 Enable or disable the types of statistics you want to display in the table.
 Table Size:  Users can select the size of the table displayed on the chart, ranging from "Tiny" to "Auto," which adjusts based on screen size.
 Table Position:  Users can choose the location of the table on the chart
 
----------------- 
Disclaimer 
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information. 
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs. 
 My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes! 
MACD_TRIGGER_CROSS_TRIANGLEMACD Triangle Trigger Indicator by thebearfib 
 Overview 
The MACD Cross Triangle Indicator is a powerful tool for traders who rely on the MACD's signal line crossovers to make informed trading decisions. This indicator enhances the traditional MACD by allowing users to customize triggers for bullish and bearish signals and by displaying these signals directly on the chart with visually distinctive labels.
 Features 
 Customizable Color Scheme: Choose distinct colors for bullish and bearish signals to fit your chart's theme or your personal preference.
 Flexible Trigger Conditions:  Select from a variety of trigger conditions based on MACD and signal line behaviors over a specified number of bars back.
 Visual Signal Indicators:  Bullish and bearish signals are marked with upward and downward triangles, making it easy to spot potential entry or exit points.
 Detailed Trigger Descriptions:  A comprehensive table lists all available triggers and their descriptions, aiding in selection and understanding of each trigger's mechanism.
 Configuration Options 
 Bullish and Bearish Colors:  Customize the color of the labels for bullish (upward) and bearish (downward) signals.
 Trend Lookback Period:  Choose how far back (in bars) the indicator should look to determine the trend, affecting the calculation of certain triggers.
 Trigger Selection for Bullish and Bearish Signals:  Pick specific triggers for both bullish and bearish conditions from a list of 10 different criteria, ranging from MACD crossovers to historical comparisons of MACD, signal line, and histogram values.
 Label Size and Font Settings:  Adjust the size of the signal labels on the chart and the font size of the trigger descriptions table to ensure readability and fit with your chart layout.
 Trigger Descriptions Table Position and Color:  Customize the position and color of the trigger descriptions table to match your chart's aesthetic and layout preferences.
 Trigger Mechanisms 
 Trigger 1 to 10:  Each trigger corresponds to a specific condition involving the MACD line, signal line, and histogram. These include crossovers, directional changes compared to previous bars, and comparisons of current values to historical values.
 Usage 
 1. Select Trigger Conditions:  Choose the desired triggers for bullish and bearish signals based on your trading strategy.
 2. Customize Visuals:  Set your preferred colors for the bullish and bearish labels, adjust label and font sizes, and configure the trigger descriptions table.
 3. Analyze Signals:  Watch for the upward (bullish) and downward (bearish) triangles to identify potential trading opportunities based on MACD crossover signals.
 Conclusion 
The MACD Cross Triangle Indicator offers a customizable and visually intuitive way to leverage MACD crossover signals for trading. With its flexible settings and clear signal indicators, traders can tailor the indicator to fit their strategy and improve their decision-making process on TradingView.
Divergence AnalyzerUnlock the potential of your trading strategy with the Divergence Analyzer, a sophisticated indicator designed to identify divergence patterns between two financial instruments. Whether you're a seasoned trader or just starting, this tool provides valuable insights into market trends and potential trading opportunities.
Key Features:
1. Versatility in Symbol Selection:
- Choose from a wide range of symbols for comparison, including popular indices like XAUUSD and SPX.
- Seamlessly toggle between symbols to analyze divergences and make informed trading decisions.
2. Flexible Calculation Options:
- Customizable options allow you to use a different symbol for calculation instead of the chart symbol.
- Fine-tune your analysis by selecting specific symbols for comparison based on your trading preferences.
3. Logarithmic Scale Analysis:
- Utilizes logarithmic scales for accurate representation of price movements.
- Linear regression coefficients are calculated on the logarithmic scale, providing a comprehensive view of trend strength.
4. Dynamic Length and Smoothing:
- Adjust the length parameter to adapt the indicator to different market conditions.
- Smoothed linear regression with exponential moving averages enhances clarity and reduces noise.
5. Standard Deviation Normalization:
- Normalizes standard deviations over 200 periods, offering a standardized view of price volatility.
- Easily compare volatility levels across different symbols for effective divergence analysis.
6. Color-Coded Divergence Visualization:
- Clearly distinguish positive and negative divergences with customizable color options.
- Visualize divergence deltas with an intuitive color scheme for quick and effective interpretation.
7. Symbol Information Table:
- An included table provides at-a-glance information about the selected symbols.
- Identify Symbol 1 and Symbol 2, along with their corresponding positive and negative divergence colors.
How to Use:
1. Select symbols for analysis using the user-friendly inputs.
2. Customize calculation options based on your preferences.
3. Analyze the divergence delta plot for clear visual indications.
4. Refer to the symbol information table for a quick overview of selected instruments.
Empower your trading strategy with the Divergence Analyzer and gain a competitive edge in the dynamic world of financial markets. Start making more informed decisions today!
Z-ScoreThe "Z-Score" indicator is a unique and powerful tool designed to help traders identify overbought and oversold conditions in the market. Below is an explanation of its features, usefulness, and what makes it special:
 Features: 
 Z-Score Calculation:  The indicator calculates the Z-Score, a statistical measure that represents how far the current price is from the moving average (MA) in terms of standard deviations. It helps identify extreme price movements.
 Customizable Parameters:  Traders can adjust key parameters such as the Z-Score threshold, the type of MA (e.g., SMA, EMA), and the length of the moving average to suit their trading preferences.
 Signal Options:  The indicator offers flexibility in terms of signaling. Traders can choose whether to trigger signals when the Z-Score crosses the specified threshold or when it moves away from the threshold.
 Visual Signals : Z-Score conditions are represented visually on the chart with color-coded background highlights. Overbought conditions are marked with a red background, while oversold conditions are indicated with a green background.
 Information Table:  A dynamic information table displays essential details, including the MA type, MA length, MA value, standard deviation, current price, and Z-Score. This information table helps traders make informed decisions.
 Usefulness: 
 Overbought and Oversold Signals:  Z-Score is particularly valuable for identifying overbought and oversold market conditions. Traders can use this information to potentially enter or exit positions.
 Statistical Analysis:  The Z-Score provides a statistical measure of price deviation, offering a data-driven approach to market analysis.
 Customization:  Traders can customize the indicator to match their trading strategies and preferences, enhancing its adaptability to different trading styles.
 Visual Clarity:  The visual signals make it easy for traders to quickly spot potential trade opportunities on the price chart.
In summary, the Z-Score indicator is a valuable tool for traders looking to incorporate statistical analysis into their trading strategies. Its customizability, visual signals, and unique statistical approach make it an exceptional choice for identifying overbought and oversold market conditions and potential trading opportunities.
RSI Screener Multi Timeframe [5ema]This indicator is the simple version of my indicator: RSI Screener and Divergence .
 Only show table with values, signals at 5 custom timeframes. 
-----
I reused some functions, made by (i believe that):
©paaax: The table position function.
@kingthies: The RSI divergence function.
@QuantNomad: The function calculated value and array screener for 40+ instruments.
I have commented in my code. Thanks so much!
-----
 How it works: 
1. Input :
 
 Length of RSI => calculate RSI.
 Upper/lower => checking RSI overbought/oversold.
 Right bars / left bars => returns price of the pivot low & high point => checking divergence.
 Range upper / lower bars => compare the low & high point => checking divergence.
 Timeframe => request.security another time frame.
 Table position => display screener table.
 
2. Input bool:
 
 Regular Bearish divergence.
 Hidden Bullish divergence .
 Hidden Bearish divergence.
 
3. Basic calculated:
 
 Make function for RSI , pivot low & high point of RSI and price.
 Request.security that function for earch time frame.
 Result RSI, Divergence.
 
4. Condition of signal:
Buy condition:
 
 RSI oversold (1)
 Bullish divergence (2).
 
=> Buy if (1) and (2), review buy (1) or (2).
Sell condition:
 
 RSI overbought (3).
 Bearish divergence (4).
 
=> Sell if (3) and (4), review sell (3) or (4).
-----
Table screener:
 
 Time frame.
 RSI (green - oversold, red - overbought)
 Divergence (>> - regular bullish , << regular bearish , > - hidden bullish , < - hidden bearish ).
 Signal (green ⦿ - Buy, red ⦿ - Sell, green 〇 - review buy, red 〇 - review sell).
 
- Regular Bearish divergence:
- Regular Bullish divergence:
- Regular Bullish divergence + RSI overSold
- Regular Bearish divergence + RSI overBought
-----
 This indicator is for reference only, you need your own method and strategy.
If you have any questions, please let me know in the comments.
Price Range Volume Profile [Pt]█ Introduction 
The  Price Range Volume Profile (PRVP)  is a revolutionary indicator. This tool stands out from its peers due to its unique ability to capture the entire price chart history, thus providing a comprehensive volume profile of the entire asset's trading history, as available on TradingView chart. It's worth noting that I believe this tool is the first of its kind to accomplish such a feat. A much recommended tool if you are a volume profile trader. 
 █ Main Features 
►  Historical Lookback:  This feature dives deep into the past, grasping all the historical data of an asset. It's equipped to handle up to 20,000 bars, although users without a premium TradingView account are advised to keep it at a maximum of 10,000 bars, or just use the "Full Historical Lookback" feature.
►  Volume Profile / POC:  Displays the distribution of volume across price levels for the selected price range. The Point of Control (POC), which is the price level with the highest traded volume, is also highlighted.
►  Customization:  Users have the flexibility to adjust the profile's appearance, including profile width, horizontal offset, and the option to fill the background of the profile range.
►  Time Weighting:  This feature allows users to give more weight to recent trading activity, which can be especially useful for intraday traders or during times of high volatility. Note that this feature will impact the volume profile and POC level. 
►  Settings Table:  A settings table is displayed on the chart for users to quickly reference their input parameters.
 █ Input Parameters 
► Lookback Timeframe: Determines the period for which the volume profile is generated.
► Price Range: The percentage distance to consider for the profile, adjusted above and below the current closing price.
► Profile Step size: The granularity of the volume profile. Users can opt for automatic step size based on a predefined calculation or set their preferred tick step size.
► Historical Bars Lookback: Determines the number of bars to include in the volume profile calculation.
► Profile Visuals: Adjust the appearance and layout of the volume profile on the chart.
► Extra: Additional settings including the display of a settings table and its location.
 █ Basic Understanding of Volume Profile - How to use PRVP? 
Volume Profile is a valuable tool for traders who want insights into where the majority of trading activity has occurred. Here are some tips to make the most of it:
►  Understand the Basics:  Before using the Volume Profile, ensure you understand the difference between it and the standard volume histogram. While both represent volume, the former displays it against price while the latter shows it against time.
►  Identify High Volume Nodes (HVN) and Low Volume Nodes (LVN): 
     ◊  HVN:  Areas where there's a lot of trading activity and where the price has spent a lot of time. These areas can act as strong support or resistance.
     ◊  LVN:  Areas where there's a lack of trading activity. Prices might move quickly through these areas, and they can act as potential breakpoints or accelerators for price movement.
►  Locate the Point of Control (POC):  This is the price level with the highest traded volume for a specified period. It often acts as a magnet for price, and it can serve as a pivot or reference point.
►  Trend Confirmation:  A shift in the volume profile from one price level to another can confirm a trend. For instance, if higher volume starts to build at higher price levels, it may indicate a strong uptrend.
►  Watch for Volume Gaps:  If there's a significant gap in the volume profile, prices may move quickly through these levels as there's little historical trading activity to act as support or resistance.
 █ Other Usage Tips 
◊ For optimal performance, ensure that the chosen timeframe aligns closely with the chart timeframe. Differences in timeframes may lead to minor discrepancies in the volume profile.
◊ To address any errors arising from too many levels displayed on the volume profile, consider increasing the Profile Step size or reducing the Price Range.
AI-Bank-Nifty Tech AnalysisThis code is a TradingView indicator that analyzes the Bank Nifty index of the Indian stock market. It uses various inputs to customize the indicator's appearance and analysis, such as enabling analysis based on the chart's timeframe, detecting bullish and bearish engulfing candles, and setting the table position and style.
The code imports an external script called BankNifty_CSM, which likely contains functions that calculate technical indicators such as the RSI, MACD, VWAP, and more. The code then defines several table cell colors and other styling parameters.
Next, the code defines a table to display the technical analysis of eight bank stocks in the Bank Nifty index. It then defines a function called get_BankComponent_Details that takes a stock symbol as input, requests the stock's OHLCV data, and calculates several technical indicators using the imported CSM_BankNifty functions.
The code also defines two functions called get_EngulfingBullish_Detection and get_EngulfingBearish_Detection to detect bullish and bearish engulfing candles.
Finally, the code calculates the technical analysis for each bank stock using the get_BankComponent_Details function and displays the results in the table. If the engulfing input is enabled, the code also checks for bullish and bearish engulfing candles and displays buy/sell signals accordingly.
The FRAMA stands for "Fractal Adaptive Moving Average," which is a type of moving average that adjusts its smoothing factor based on the fractal dimension of the price data. The fractal dimension reflects self-similarity at different scales. The FRAMA uses this property to adapt to the scale of price movements, capturing short-term and long-term trends while minimizing lag. The FRAMA was developed by John F. Ehlers and is commonly used by traders and analysts in technical analysis to identify trends and generate buy and sell signals. I tried to create this indicator in Pine.
In this context, "RS" stands for "Relative Strength," which is a technical indicator that compares the performance of a particular stock or market sector against a benchmark index.
The "Alligator" is a technical analysis tool that consists of three smoothed moving averages. Introduced by Bill Williams in his book "Trading Chaos," the three lines are called the Jaw, Teeth, and Lips of the Alligator. The Alligator indicator helps traders identify the trend direction and its strength, as well as potential entry and exit points. When the three lines are intertwined or close to each other, it indicates a range-bound market, while a divergence between them indicates a trending market. The position of the price in relation to the Alligator lines can also provide signals, such as a buy signal when the price crosses above the Alligator lines and a sell signal when the price crosses below them.
In addition to these, we have several other commonly used technical indicators, such as MACD, RSI, MFI (Money Flow Index), VWAP, EMA, and Supertrend. I used all the built-in functions for these indicators from TradingView. Thanks to the developer of this TradingView Indicator.
I also created a BankNifty Components Table and checked it on the dashboard.
Candle Counter [theEccentricTrader]█   OVERVIEW 
This indicator counts the number of confirmed candle scenarios on any given candlestick chart and displays the statistics in a table, which can be repositioned and resized at the user's discretion. 
█   CONCEPTS  
 Green and Red Candles 
 
 A green candle is one that closes with a high price equal to or above the price it opened. 
 A red candle is one that closes with a low price that is lower than the price it opened. 
 
 Upper Candle Trends 
 
 A higher high candle is one that closes with a higher high price than the high price of the preceding candle.
 A lower high candle is one that closes with a lower high price than the high price of the preceding candle. 
 A double-top candle is one that closes with a high price that is equal to the high price of the preceding candle.
 
 Lower Candle Trends 
 
 A higher low candle is one that closes with a higher low price than the low price of the preceding candle. 
 A lower low candle is one that closes with a lower low price than the low price of the preceding candle.
 A double-bottom candle is one that closes with a low price that is equal to the low price of the preceding candle.
 
█   FEATURES 
 Inputs 
 
 Start Date
 End Date 
 Position 
 Text Size 
 Show Sample Period 
 Show Plots 
 
 Table 
The table is colour coded, consists of three columns and twenty-two rows. Blue cells denote all candle scenarios, green cells denote green candle scenarios and red cells denote red candle scenarios. 
The candle scenarios are listed in the first column with their corresponding total counts to the right, in the second column. The last row in column one, row twenty-two, displays the sample period which can be adjusted or hidden via indicator settings.
Rows two and three in the third column of the table display the total green and red candles as percentages of total candles. Rows four to nine in column three, coloured blue, display the corresponding candle scenarios as percentages of total candles. Rows ten to fifteen in column three, coloured green, display the corresponding candle scenarios as percentages of total green candles. And lastly, rows sixteen to twenty-one in column three, coloured red, display the corresponding candle scenarios as percentages of total red candles.
 Plots 
I have added plots as a visual aid to the various candle scenarios listed in the table. Green up-arrows denote higher high candles when above bar and higher low candles when below bar. Red down-arrows denote lower high candles when above bar and lower low candles when below bar. Similarly, blue diamonds when above bar denote double-top candles and when below bar denote double-bottom candles. These plots can also be hidden via indicator settings. 
█   HOW TO USE 
 
This indicator is intended for research purposes and strategy development. I hope it will be useful in helping to gain a better understanding of the underlying dynamics at play on any given market and timeframe. It can, for example, give you an idea of any inherent biases such as a greater proportion of green candles to red. Or a greater proportion of higher low green candles to lower low green candles. Such information can be very useful when conducting top down analysis across multiple timeframes, or considering trailing stop loss methods. 
What you do with these statistics and how far you decide to take your research is entirely up to you, the possibilities are endless. 
This is just the first and most basic in a series of indicators that can be used to study objective price action scenarios and develop a systematic approach to trading. 
█   LIMITATIONS 
 
Some higher timeframe candles on tickers with larger lookbacks such as the DXY, do not actually contain all the open, high, low and close (OHLC) data at the beginning of the chart. Instead, they use the close price for open, high and low prices. So, while we can determine whether the close price is higher or lower than the preceding close price, there is no way of knowing what actually happened intra-bar for these candles. And by default candles that close at the same price as the open price, will be counted as green. You can avoid this problem by utilising the sample period filter.
 
The green and red candle calculations are based solely on differences between open and close prices, as such I have made no attempt to account for green candles that gap lower and close below the close price of the preceding candle, or red candles that gap higher and close above the close price of the preceding candle. I can only recommend using 24-hour markets, if and where possible, as there are far fewer gaps and, generally, more data to work with. Alternatively, you can replace the scenarios with your own logic to account for the gap anomalies, if you are feeling up to the challenge.
It is also worth noting that the sample size will be limited to your Trading View subscription plan. Premium users get 20,000 candles worth of data, pro+ and pro users get 10,000, and basic users get 5,000. If upgrading is currently not an option, you can always keep a rolling tally of the statistics in an excel spreadsheet or something of the like. 
ConsoleLibrary   "Console" 
█   OVERVIEW 
An easy way to output messages to a console like table using a a simple "print" function that can be called from anywhere in your code including functions.
█   Supports: 
    -    Scrollable console messages
    -    Customisable number of displayed messages
    -    More than one "console" for different types of output if required
    -    The ability to choose which message to start viewing from (useful if the message list is long)
    -    The ability to place the console table at different positions on the chart to mitigate against
     overwriting an existing table.
█   Limitations: 
The "scrollbar" handle is actually a modified time widget handle. As the handle is grabbed and moved left or right across the chart bars, this script calculates the offset of the bar being pointed to from the last bar in the chart and uses that as the console message offset. However, It isn't possible to position this on the last chart bar with code.
So there are two solutions:
1) Manually change timestamp of the variable scrollStart  to the current time (roughly) 
eg. scrollStart = "25 Dec 2022 14:30 +0000"
2) Use a higher timeframe (Weeks or Months) and visually find the scroll bar. If it is to the right of the chart bars the console output will read NaN. Grab the handle and move it left and it will snap to the last chart candle position. If it is to the left then find it and move it to the right as needed.
█   Notes On Usage 
    -    Import the library as console (the call will be console.print(...) )
    -    Assign a console variable name and call the console.initialise function
     eg. var con1=console.initialise()
    -    Use the console.print() function to print a message or messages 
     This takes two parameters: 
     _consoleName :this is the console name you are printing to
     _message: this is the message that you want to display. It is a string and can be built in the normal way using any pinescript string functions like str.tostring() etc
    -    Use the console.display function to display the messages.
To work as intended this display function should be placed at the last line with the following code
if i_showMessages
....if i_displayTable == "con1" 
........display(con1, i_lineOffset, i_rowsToDisplay, i_gotoMsg, posn)
(More "consoles" can be written to and the example code provided with the library shows this in more detail. Also, the indents don't show in these notes)
Lastly, placement of a console.print() without a qualifying "if" statement will  occur for every bar. This may be desired. If not then use under an if statement (example in the supplied code).
Happy debugging :)
-----------------------------------------------------------------------------------------------------------
 initialise() 
  initialise: creates the message array
  Parameters:
     none :
  Returns: message array: this is assigned to the "console" identifier
 print(_consoleName, _message) 
  used to output the desired text string to the console
  Parameters:
     _consoleName : : the message array
     _message : : the console message
  Returns: none
 display(_consoleName, _lineOffset, _rowsToDisplay, _gotoMsg, _posn) 
  display: placed in the last section of code. Displays the console messages
  Parameters:
     _consoleName : : the message array
     _lineOffset : : the setting of the scroll bar (time widget)
     _rowsToDisplay : : how many rows to show in the console table
     _gotoMsg : : which message to display from (default is 0)
     _posn : : where the console table will be displayed
  Returns: none
_matrixLibrary   "_matrix" 
Library helps visualize matrix as array of arrays and enables users to use array methods such as push, pop, shift, unshift etc along with cleanup activities on drawing objects wherever required
 unshift(mtx, row)  unshift array of lines to first row of the matrix
  Parameters:
     mtx : matrix of lines
     row : array of lines to be inserted in row 
  Returns: resulting matrix of lines
 unshift(mtx, row)  unshift array of labels to first row of the matrix
  Parameters:
     mtx : matrix of labels
     row : array of labels to be inserted in row 
  Returns: resulting matrix labels
 unshift(mtx, row)  unshift array of boxes to first row of the matrix
  Parameters:
     mtx : matrix of boxes
     row : array of boxes to be inserted in row 
  Returns: resulting matrix of boxes
 unshift(mtx, row)  unshift array of linefill to first row of the matrix
  Parameters:
     mtx : matrix of linefill
     row : array of linefill to be inserted in row 
  Returns: resulting matrix of linefill
 unshift(mtx, row)  unshift array of tables to first row of the matrix
  Parameters:
     mtx : matrix of tables
     row : array of tables to be inserted in row 
  Returns: resulting matrix of tables
 unshift(mtx, row)  unshift array of int to first row of the matrix
  Parameters:
     mtx : matrix of int
     row : array of int to be inserted in row 
  Returns: resulting matrix of int
 unshift(mtx, row)  unshift array of float to first row of the matrix
  Parameters:
     mtx : matrix of float
     row : array of float to be inserted in row 
  Returns: resulting matrix of float
 unshift(mtx, row)  unshift array of bool to first row of the matrix
  Parameters:
     mtx : matrix of bool
     row : array of bool to be inserted in row 
  Returns: resulting matrix of bool
 unshift(mtx, row)  unshift array of string to first row of the matrix
  Parameters:
     mtx : matrix of string
     row : array of string to be inserted in row 
  Returns: resulting matrix of string
 unshift(mtx, row)  unshift array of color to first row of the matrix
  Parameters:
     mtx : matrix of colors
     row : array of colors to be inserted in row 
  Returns: resulting matrix of colors
 push(mtx, row)  push array of lines to end of the matrix row
  Parameters:
     mtx : matrix of lines
     row : array of lines to be inserted in row 
  Returns: resulting matrix of lines
 push(mtx, row)  push array of labels to end of the matrix row
  Parameters:
     mtx : matrix of labels
     row : array of labels to be inserted in row 
  Returns: resulting matrix of labels
 push(mtx, row)  push array of boxes to end of the matrix row
  Parameters:
     mtx : matrix of boxes
     row : array of boxes to be inserted in row 
  Returns: resulting matrix of boxes
 push(mtx, row)  push array of linefill to end of the matrix row
  Parameters:
     mtx : matrix of linefill
     row : array of linefill to be inserted in row 
  Returns: resulting matrix of linefill
 push(mtx, row)  push array of tables to end of the matrix row
  Parameters:
     mtx : matrix of tables
     row : array of tables to be inserted in row 
  Returns: resulting matrix of tables
 push(mtx, row)  push array of int to end of the matrix row
  Parameters:
     mtx : matrix of int
     row : array of int to be inserted in row 
  Returns: resulting matrix of int
 push(mtx, row)  push array of float to end of the matrix row
  Parameters:
     mtx : matrix of float
     row : array of float to be inserted in row 
  Returns: resulting matrix of float
 push(mtx, row)  push array of bool to end of the matrix row
  Parameters:
     mtx : matrix of bool
     row : array of bool to be inserted in row 
  Returns: resulting matrix of bool
 push(mtx, row)  push array of string to end of the matrix row
  Parameters:
     mtx : matrix of string
     row : array of string to be inserted in row 
  Returns: resulting matrix of string
 push(mtx, row)  push array of colors to end of the matrix row
  Parameters:
     mtx : matrix of colors
     row : array of colors to be inserted in row 
  Returns: resulting matrix of colors
 shift(mtx)  shift removes first row from matrix of lines
  Parameters:
     mtx : matrix of lines from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of labels
  Parameters:
     mtx : matrix of labels from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of boxes
  Parameters:
     mtx : matrix of boxes from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of linefill
  Parameters:
     mtx : matrix of linefill from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of tables
  Parameters:
     mtx : matrix of tables from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of int
  Parameters:
     mtx : matrix of int from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of float
  Parameters:
     mtx : matrix of float from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of bool
  Parameters:
     mtx : matrix of bool from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of string
  Parameters:
     mtx : matrix of string from which the shift operation need to be performed
  Returns: void
 shift(mtx)  shift removes first row from matrix of colors
  Parameters:
     mtx : matrix of colors from which the shift operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of lines
  Parameters:
     mtx : matrix of lines from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of labels
  Parameters:
     mtx : matrix of labels from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of boxes
  Parameters:
     mtx : matrix of boxes from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of linefill
  Parameters:
     mtx : matrix of linefill from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of tables
  Parameters:
     mtx : matrix of tables from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of int
  Parameters:
     mtx : matrix of int from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of float
  Parameters:
     mtx : matrix of float from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of bool
  Parameters:
     mtx : matrix of bool from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of string
  Parameters:
     mtx : matrix of string from which the pop operation need to be performed
  Returns: void
 pop(mtx)  pop removes last row from matrix of colors
  Parameters:
     mtx : matrix of colors from which the pop operation need to be performed
  Returns: void
 clear(mtx)  clear clears the matrix of lines
  Parameters:
     mtx : matrix of lines which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of labels
  Parameters:
     mtx : matrix of labels which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of boxes
  Parameters:
     mtx : matrix of boxes which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of linefill
  Parameters:
     mtx : matrix of linefill which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of tables
  Parameters:
     mtx : matrix of tables which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of int
  Parameters:
     mtx : matrix of int which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of float
  Parameters:
     mtx : matrix of float which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of bool
  Parameters:
     mtx : matrix of bool which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of string
  Parameters:
     mtx : matrix of string which needs to be cleared
  Returns: void
 clear(mtx)  clear clears the matrix of colors
  Parameters:
     mtx : matrix of colors which needs to be cleared
  Returns: void
Logging in Pine ScriptI'm building quite a lot of pretty complicated indicators/strategies in Pine Script. Quite often they don't work from the 1 try so I have to debug them heavily. 
In Pine Script there are no fancy debuggers so you have to be creative. You can plot values on your screens, check them in the data window, etc.  
If you want to display some textual information, you can plot some info as labels on the screen. 
It's not the most convenient way, so with the appearance of tables in Pine Script, I decided to implement a custom logger that will allow me to track some useful information about my indicator over time.
Tables work much better for this kind of thing than labels. They're attached to your screen, you can nicely scale them and you can style them much better. 
The idea behind it is very simple. I used few arrays to store the message, bar number, timestamp, and type of the message (you can color messages depend on the type for example). 
There is a function  log_msg  that just append new messages to these arrays. 
In the end, for the last bar, I create the table and display the last X messages in it. 
In parameters, you can show/hide the entire journal, change the number of messages displayed and choose an offset. With offset, you can basically scroll through the history of messages. 
Currently, I implemented 3 types of messages, and I color messages according to these types:  
 
  Message - gray
  Warning - yellow
  Error - red
 
Of course, it's a pretty simple example, you can create a much fancier way of styling your logs. 
What do you think about it? Is it useful for you? What do you use to debug code in Pine Script? 
 Disclaimer 
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as good as in historical backtesting.
This post and the script don’t provide any financial advice.
Daily GAP StatsI did not write the script from scratch but rather started editing code of an existing one. The original code came from a script called GAP DETECTOR by @Asch- 
 First up: I am a trader, not a programmer and therefore my code most likely is inefficient. If someone with more expertise would like to help and optimize it - feel free to get in touch, I am always happy to learn some new tricks. :) 
This script does 2 things:
- It shows daily gaps stats based on user inputs
- It shows color coded labels on gap days with additional information in tooltips ( important: make sure to read 'known issues/limitations' at the end )
 
User Inputs
========== 
Although the input dialog is pretty straight forward, I do a quick rundown:
 - Length:  max lookback time
 - Gap Direction:  self explanatory
 - Show All Gaps | Cont Only | Reversal Only | Off:  
This refers to the way labels are displayed on gap days (again: make sure to read known issues/limitations!)
- Show All Gaps: does what it says
- Cont Only: only shows gaps where price continued in the gap direction. If you filter for gap ups and chose 'Cont only' you will only see labels on gap days where price closed above the open (and vice versa if you scan for gap downs). 
- Reversal Only: you will only see labels for closes below the open on gap up days (and the opposite on gap down days)
- Off: self explanatory
 - Gap Measure in ATR/PCT:  self explanatory, ATR is calculated over a 10d period
 - Gap Size (Abs Values):  no negative values allowed here. If you filter for gap downs and enter 3 it means it will show gaps where the stock fell more than 3 ATR/PCT on the open. 
 - RVOL Factor:  along with significant gaps should come significant volume. RVOL = volume of the gap day / 20d average volume
 - Viewing Options:  Placing the stats label in the window is a bit tricky (see knonw issues/limitations) and I was not sure which way I liked better. See for yourself what works best for you. 
 Known Isusses/Limitations:
======================= 
 - Positioning of the stats table:  
As to my knowledge, Tradingview only allows label positioning relative to price and not relative to the chart window. I tried to always display the gap stats table in the upper right corner, using 52wk high as y-coordinate. This works ok most of the time, but is not pretty. If anybody has some fancy way to tag the label in a fixed position, please get in touch. 
 - Max number of labels per script: 
TradingView has a limitation that allows a maxium of ~50 labels per script. If there are more labels, TradingView will automatically cut the oldest ones, without any notification. I have found this behaviour to be rather inconsistent - sometimes it'll dump labels even if there are a lot fewer than 50. Hopefully TradingView will drop this limitation at one point in the future. 
Important: The inconsistent display of the gap day labels has NO INFLUENCE on the calculations in the gap stats table - the count and the calculations are complete and correct!
Serenity Model VIPI — by yuu_iuHere’s a concise, practical English guide for Serenity Model VIPI (Author: yuu_iu). It covers what it is, how to set it up for daily trading, how to tune it, and how we guarantee non-repainting.
Serenity Model VIPI — User Guide (Daily Close, Non‑Repainting)
Credits
- Author: yuu_iu
- Producer: yuu_iu
- Platform: TradingView (Pine Script v5)
1) What it is
Serenity Model VIPI is a multi‑module, context‑aware trading model that fuses signals from:
- Entry modules: VCP, Flow, Momentum, Mean Reversion, Breakout
- Exit/risk modules: Contrarian, Breakout Sell, Volume Delta Sell, Peak Detector, Overbought Exit, Profit‑Take
- Context/memory: Learns per Ticker/Sector/Market Regime and adjusts weights/aggression
- Learning engine: Runs short “fake trades” to learn safely before scaling real trades
It produces a weighted, context‑adjusted score and a final decision: BUY, SELL, TAKE_PROFIT, or WAIT.
2) How it works (high level)
- Each module computes a score per bar.
- A fusion layer combines module scores using accuracy and base weights, then adjusts by:
  - Market regime (Bull/Bear/Sideways) and optional higher‑timeframe (HTF) bias
  - Risk control neuron
  - Context memory (ticker/sector/regime)
- Optional LLM mode can override marginal cases if context supports it.
- Final decision is taken at bar close only (no intrabar repaint).
3) Non‑repainting guarantee (Daily)
- Close‑only execution: All key actions use barstate.isconfirmed, so signals/entries/exits only finalize after the daily candle closes.
- No lookahead on HTF data: request.security() reads prior‑bar values (series ) for HTF close/EMA/RSI.
- Alerts at bar close: Alerts are fired once per bar close to prevent mid‑bar changes.
What this means: Once the daily bar closes, the decision and alert won’t be repainted.
4) Setup (TradingView)
- Paste the Pine v5 code into Pine Editor, click Add to chart.
- Timeframe: 1D (Daily).
- Optional: enable a date window for training/backtest
  - Enable Custom Date Filter: ON
  - Set Start Date / End Date
- Create alert (non‑repainting)
  - Condition: AI TRADE Signal
  - Options: Once Per Bar Close
  - Webhook (optional): Paste your URL into “System Webhook URL (for AI events)”
- Watch the UI
  - On‑chart markers: AI BUY / AI SELL / AI TAKE PROFIT
  - Right‑side table: Trades, Win Rate, Avg Profit, module accuracies, memory source, HTF trend, etc.
  - “AI Thoughts” label: brief reasoning and debug lines.
5) Daily trading workflow
- The model evaluates at daily close and may:
  - Enter long (BUY) when buy votes + total score exceed thresholds, after context/risk checks
  - Exit via trailing stop, hard stop, TAKE_PROFIT, or SELL decision
- Learning mode:
  - Triggers short “fake trades” every N bars (default 3) and measures outcome after 5 bars
  - Improves module accuracies and adjusts aggression once stable (min fake win% threshold)
- Memory application:
  - When you change tickers, the model tries to apply Ticker or Sector memory for the current market regime to pre‑bias module weights/aggression.
6) Tuning (what to adjust and why)
Core controls
- Base Aggression Level (default 1.0): Higher = more trades and stronger decisions; start conservative on Daily (1.0–1.2).
- Learning Speed Multiplier (default 3): Faster adaptation after fake/real trades; too high can overreact.
- Min Fake Win Rate to Exit Learning (%) (default 10–20%): Raises the bar before trusting more real trades.
- Fake Trade Every N Bars (default 3): Frequency of learning attempts.
- Learning Threshold Win Rate (default 0.4): Governs when the learner should keep learning.
- Hard Stop Loss (%) (default 5–8%): Global emergency stop.
Multi‑Timeframe (MTF)
- Enable Multi‑Timeframe Confirmation: ON (recommended for Daily)
- HTF Trend Source: HOSE:VNINDEX for VN equities (or CURRENT_SYMBOL if you prefer)
- HTF Timeframe: D or 240 (for a strong bias)
- MTF Weight Adjustment: 0.2–0.4 (0.3 default is balanced)
Module toggles and base weights
- In strong uptrends: increase VCP, Momentum, Breakout (0.2–0.3 typical)
- In sideways low‑vol regimes: raise MeanRev (0.2–0.3)
- For exits/defense: Contrarian, Peak, Overbought Exit, Profit‑Take (0.1–0.2 each)
- Keep Flow on as a volume‑quality filter (≈0.2)
Memory and control
- Enable Shared Memory Across Tickers: ON to share learning
- Enable Sector‑Based Knowledge Transfer: ON to inherit sector tendencies
- Manual Reset Learning: Use sparingly to reset module accuracies if regime changes drastically
Risk management
- Hard Stop Loss (%): 5–8% typical on Daily
- Trailing Stop: ATR‑ and volatility‑adaptive; tightens faster in Bear/High‑Vol regimes
- Max hold bars: Shorter in Bear or Sideways High‑Vol to cut risk
Alerts and webhook
- Use AI TRADE Signal with Once Per Bar Close
- Webhook payload is JSON, including event type, symbol, time, win rates, equity, aggression, etc.
7) Recommended Daily preset (VN equities)
- MTF: Enable, Source: HOSE:VNINDEX, TF: D, Weight Adj: 0.3
- Aggression: 1.1
- Learning Speed: 3
- Min Fake Win Rate to Exit Learning: 15%
- Hard SL: 6%
- Base Weights:
  - VCP 0.25, Momentum 0.25, Breakout 0.15, Flow 0.20
  - MeanRev 0.20 (raise in sideways)
  - Contrarian/Peak/Overbought/Profit‑Take: 0.10–0.20
- Leave other defaults as is, then fine‑tune by symbol/sector.
8) Reading the UI
- Table highlights: Real Trades, Win Rate, Avg Profit, Fake Actions/Win%, VCP Acc, Aggression, Equity, Score, Status (LEARNING/TRADING/REFLECTION), Last Real, Consec Loss, Best/Worst Trade, Pattern Score, Memory Source, Current Sector, AI Health, HTF Trend, Scheduler, Memory Loaded, Fake Active.
- Shapes: AI BUY (below bar), AI SELL/TAKE PROFIT (above bar)
- “AI Thoughts”: module contributions, context notes, debug lines
9) Troubleshooting
- No trades?
  - Ensure timeframe is 1D and the date filter covers the chart range
  - Check Scheduler Cooldown (3 bars default) and that barstate.isconfirmed (only at close)
  - If MTF is ON and HTF is bearish, buy bias is reduced; relax MTF Weight Adjustment or module weights
- Too many/too few trades?
  - Lower/raise Base Aggression Level
  - Adjust base weights on key modules (raise entry modules to be more active; raise exit/defense modules to be more selective)
- Learning doesn’t end?
  - Increase Min Fake Win Rate to Exit Learning only after it’s consistently stable; otherwise lower it or reduce Fake Trade Every N Bars
10) Important notes
- The strategy is non‑repainting at bar close by design (confirmed bars + HTF series  + close‑only alerts).
- Backtest fills may differ from live fills due to slippage and broker rules; this is normal for all TradingView strategies.
- Always validate settings across multiple symbols and regimes before going live.
If you want, I can bundle this guide into a README section in your Pine code and add a small on‑chart signature (Author/Producer: yuu_iu) in the top‑right corner.






















